#!/usr/bin/python
# -*- coding:utf-8 -*-
# @Time  : 7/8/20
# @Author: yanlh
# @usage : 第三方开源docker-bench-security
import os
import sys

sys.path.append('..')
from common_utils import CBBCommonUtils

path = os.path.dirname(os.path.join(os.getcwd(), '../..'))
sys.path.append(os.path.join(path, 'plugins/secchecksuite/docker'))
import docker_utils


def get_plugin_info():
    plugin_info = {
        "name": "docker_bench_security docker",
        "plugin_id": "docker_bench_security",
        "plugin_type": "docker third develop",
        "info": "scan docker according to CIS",
        "level": "B",
        "module": "Safety scan",
        "author": "yanlh",
        "keyword": "Safety scan",
        "configable": "false",
    }
    return plugin_info


logger = None
cur_user = None
cur_module = None
cur_task = None


def set_plugin_logger(setter, user, module, task, *args, **kwargs):
    global logger, cur_user, cur_module, cur_task
    logger = setter
    cur_user = user
    cur_module = module
    cur_task = task


def single_logger_record(level, des, module='_Scan'):
    if level == 'error':
        logger.debug_error(cur_user, cur_module, cur_task + module, '', des)
    if level == 'info':
        logger.debug_info(cur_user, cur_module, cur_task + module, '', des)
    if level == 'warning':
        logger.debug_warning(cur_user, cur_module, cur_task + module, '', des)


def execute_scan(func_args):
    os.chdir(os.path.join(os.getcwd(), '../'))
    os.chdir(os.path.join(os.getcwd(), 'plugins/thirddevelop/docker_bench_security/'))
    cmd = './docker-bench-security.sh'
    scan_list = []
    try:
        result, output = CBBCommonUtils.cbb_run_cmd(func_args['ip'], cmd, username=func_args['username'],
                                                    passwd=func_args['passwd'])
        os.chdir(os.path.join(os.getcwd(), '../../..'))
        os.chdir(os.path.join(os.getcwd(), 'dist/'))
        for item in output:
            print(item)
            scan_list.append(item)
            single_logger_record('info', item)
        for error in result:
            print(error)
            scan_list.append(error)
            single_logger_record('info', error)
        return scan_list, 0
    except Exception as err:
        os.chdir(os.path.join(os.getcwd(), '../../..'))
        os.chdir(os.path.join(os.getcwd(), 'dist/'))
        des = 'Occure some errors: {}'.format(err)
        scan_list.append(des)
        single_logger_record('info', des)
        return scan_list, 1


# 扫描函数
def scan(func_args, flag=0):
    single_logger_record('info', "Scan Start.")
    scan_list, error_count = execute_scan(func_args)
    single_logger_record('info', 'Scan Complete.')
    if flag:
        info = reinforce()
        scan_list.extend(info)
        return scan_list, error_count
    return scan_list, error_count


def reinforce():
    info = [docker_utils.rein_info[0], docker_utils.rein_info[1]]
    single_logger_record('info', docker_utils.rein_info[0], '_Reinforce')
    single_logger_record('info', docker_utils.rein_info[1], '_Reinforce')
    return info


# 回滚函数
def rollback(func_args):
    des_list = [docker_utils.rollback_info[0], docker_utils.rollback_info[1]]
    single_logger_record('info', docker_utils.rollback_info[0], '_Rollback')
    single_logger_record('info', docker_utils.rollback_info[1], '_Rollback')
    return des_list, 0


def check(ip, *args, **kwargs):
    sys_user = kwargs.get("system_user")
    sys_pwd = kwargs.get("system_pwd")
    comm = kwargs.get("command")
    try:
        single_logger_record('info', "docker_bench_security Start.", '_Check')
        func_args = {'ip': ip, 'username': sys_user, 'passwd': sys_pwd, 'comm': comm}
        result = docker_utils.check_func(scan, rollback, func_args)
        single_logger_record('info', "docker_bench_security Complete.", '_Check')
        return result
    except Exception as er:
        code = 1
        des = ["ERROR:", str(er)]
        single_logger_record('error', des, '_Check')
        return {"code": code, "count": 0, "des": des}
